package com.company.project.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 在spring-boot方式运行的工程中在listener监听内无法使用，还未初始化到
 */
@Component
public class SpringContextHelper implements ApplicationContextAware
{

	private static ApplicationContext context;

	public void setApplicationContext(ApplicationContext context) throws BeansException
	{
		this.context = context;
	}

	public static Object getBean(String beanName)
	{
		int i = 0;
		while (context == null && i < 100)
		{
			try
			{
				Thread.sleep(10);
				i++;
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		if(context == null)
			return  null;
		return context.getBean(beanName);
	}

	public static <T> T getBean(Class<T> requiredType)
	{
		int i = 0;
		while (context == null && i < 100)
		{
			try
			{
				Thread.sleep(10);
				i++;
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		if(context == null)
			return  null;
		return context.getBean(requiredType);
	}
}
